<script setup lang="ts">
import { onUnmounted, reactive, ref, watch } from 'vue';
import type { CSSProperties } from 'vue';

const props = withDefaults(
  defineProps<{
    images: string[];
    isInitialized: boolean;
  }>(),
  {
    images: () => [] as string[],
    isInitialized: false
  }
);

const currentSrc = ref('');
const nextSrc = ref('');

const styles = reactive<{
  current: CSSProperties;
  next: CSSProperties;
}>({
  current: {
    opacity: 1,
    zIndex: 2
  },
  next: {
    opacity: 1,
    zIndex: 1
  }
});

let current = 0;
let isNext = false;
let timeoutId: NodeJS.Timeout | null = null;

const nextImage = () => {
  if (isNext) {
    styles.next.opacity = 0;
    styles.current.opacity = 1;

    setTimeout(() => {
      styles.current.zIndex = 2;
      styles.next.zIndex = 1;
      nextSrc.value = props.images[current];
    }, 1300);
  } else {
    styles.current.opacity = 0;
    styles.next.opacity = 1;

    setTimeout(() => {
      styles.next.zIndex = 2;
      styles.current.zIndex = 1;
      currentSrc.value = props.images[current];
    }, 1300);
  }

  current = (current + 1) % props.images.length;
  isNext = !isNext;
};

const startAutoSwitch = () => {
  timeoutId = setTimeout(() => {
    nextImage();
    startAutoSwitch();
  }, 5000);
};

watch(
  () => props.images,
  (images) => {
    currentSrc.value = images[current];
    nextSrc.value = images[current + 1];
    current = (current + 1) % props.images.length;
    startAutoSwitch();
  }
);

watch(
  () => props.isInitialized,
  (value) => {
    if (!value && timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }
  }
);

onUnmounted(() => {
  if (timeoutId) {
    clearTimeout(timeoutId);
    timeoutId = null;
  }
});
</script>

<template>
  <view class="image-stack">
    <image :src="currentSrc" class="stacked-image" :style="styles.current" />
    <image :src="nextSrc" class="stacked-image" :style="styles.next" />
  </view>
</template>

<style scoped>
.image-stack {
  position: relative;
  width: 750rpx;
  height: 1140rpx;
}

.stacked-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: all 1.2s ease-in-out;
}
</style>
